#include "Tile.h"

int Tile::nu=0;
 
Tile::Tile()
{
	init();
}
void Tile::init()
{
	tileImage  =SDL_CreateRGBSurface(SDL_HWSURFACE, 32, 32, 32,
		0x00, 0x00, 0x00, 0x00);
	alpha = 255;
	id = nu;
	nu++;
	drawables =* new std::vector<Drawable>();

} 
Tile::~Tile(void)
{
	delete tileImage;
	delete &drawables;
	
SDL_FreeSurface( tileImage);
}

void Tile::applyGraphics( )
{ 
	
SDL_FreeSurface( tileImage );
	tileImage  =SDL_CreateRGBSurface(SDL_HWSURFACE, 32, 32, 32,
		0x00, 0x00, 0x00, 0x00);
	std::vector<Drawable>::iterator it;
	for(it=drawables.begin(); it!=drawables.end(); it++){
		
			Draw::apply_surface(0, 0, it->graphic , this->tileImage );
			 
	}
	
	//SDL_SetAlpha(tileImage,SDL_SRCALPHA, alpha);
}

void Tile::removeDrawable(int id)
{

	std::vector<Drawable>::iterator it; 

	for(it=drawables.begin(); it!=drawables.end(); it++)
		if(it->uid == id){
			drawables.erase(it);
			break;
		}
		this->applyGraphics();

}

void Tile::addDrawable(Drawable* thing)
{

	drawables.push_back(*thing);

}

bool Tile::Collides(int layer)//pass this method a negative number if you want ANY collision. layer zero is NON collidables
{
	std::vector<Drawable>::iterator it; 
	if(layer>0){
	for(it=drawables.begin(); it!=drawables.end(); it++)
		if(it->collides == layer){
			return true;
			break;
		}
	}
	else if(layer<0)
	{
	for(it=drawables.begin(); it!=drawables.end(); it++)
		if(it->collides >0){
			return true;
			break;
		}

	}
	//if it hasn't returned true at this point, there are no collisions
	return false;
		



}

double Tile::getLightEmitted() const
{
	int maxLight = 0;
	std::vector<Drawable>::const_iterator it;
	for(it=drawables.cbegin(); it!=drawables.cend(); it++){
		if(it->lightEmitted>maxLight)
		{
			maxLight = it->lightEmitted;
		}
			 
	}
	return maxLight;
}

Drawable* Tile::getEmitter() const
{
	int maxLight = 0;
	std::vector<Drawable>::const_iterator it;
	for(it=drawables.cbegin(); it!=drawables.cend(); it++){
		if(it->lightEmitted>maxLight)
		{
			maxLight = it->lightEmitted;
		}
			 
		for(it=drawables.begin(); it!=drawables.end(); it++){
		if(it->lightEmitted==maxLight)
		{
			return it._Ptr;
		}
	}


	}}

void Tile::setAlpha(int a)
{
	this->alpha = a;
 
}